<template>
<div class="body">
  <ul class="bg-bubbles">
    <li v-for="i in 13" :key="i"></li>
  </ul>

  <div class="site-wrapper site-page--login">
    <div class="site-content__wrapper">
      <div class="site-content">
        <div class="brand-info">
          <img src="../../assets/img/index.jpg" width="100%" height="100%" />
          <!-- <h1 class="brand-info__text">智慧生活</h1>
            <p class="brand-info__intro">www.shujuxiaoyuan.com</p>-->
        </div>
        <div class="login-main">
          <h3 class="login-title">智慧生活平台</h3>
          <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" status-icon>
            <el-form-item prop="userName">
              <el-input v-model="dataForm.userName" placeholder="帐号">
                <i slot="prefix" style="    line-height: 36px;">
                  <icon-svg name="yonghu" class="site-sidebar__menu-icon"></icon-svg>
                </i>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm.password" type="password" placeholder="密码" show-password>
                <i slot="prefix" style="    line-height: 36px;font-size:18px">
                  <icon-svg name="mima" class="site-sidebar__menu-icon"></icon-svg>
                </i>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model="dataForm.captcha" placeholder="验证码">
                    <i slot="prefix" style="    line-height: 36px;">
                      <icon-svg name="yanzhengma" class="site-sidebar__menu-icon"></icon-svg>
                    </i>
                  </el-input>
                </el-col>
                <el-col :span="10" class="login-captcha">
                  <img :src="captchaPath" @click="getCaptcha()" alt height="36px" />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-button class="login-btn-submit" type="primary" @click="dataFormSubmit()">登录</el-button>
            </el-form-item>
          </el-form>
          <div class="login-info">使用Chrome浏览器打开性能更佳！</div>
        </div>
      </div>
    </div>
  </div>
  <div class="site-content_down">
    <div class="site-content_meng" @click="downloadFile">下载卡务软件</div>
  </div>
</div>
</template>

<script>
import {
  getUUID
} from "@/utils";
import {
  JSEncrypt
} from "jsencrypt";
export default {
  data() {
    return {
      dataForm: {
        userName: "",
        password: "",
        uuid: "",
        captcha: "",
      },
      messageType: 0,
      publicKey: "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx8wyZzYxaffWrJ4jooN554npe5vD2RSQGNXOY5UZz6hcIW0jdEk1KcdclE7mJPiI2DmgUjBp4Lau+bNmZxmLBqFHUMd29mWyqX+LuYVoymxs8f3VJF+7PqZzuKbtSOyXfcyjIIgtB06YlX4SXx4FCErGRx+MDseN2ObHSPme/3wIDAQAB",
      dataRule: {
        userName: [{
          required: true,
          message: "帐号不能为空",
          trigger: "blur"
        }, ],
        password: [{
          required: true,
          message: "密码不能为空",
          trigger: "blur"
        }, ],
        captcha: [{
          required: true,
          message: "验证码不能为空",
          trigger: "blur"
        }, ],
      },
      captchaPath: "",
    };
  },
  computed: {
    sidebarLayoutSkin: {
      get() {
        return this.$store.state.common.sidebarLayoutSkin
      },
      set(val) {
        this.$store.commit('common/updateSidebarLayoutSkin', val)
      }
    }
  },
  created() {
    // 从cookie获取登录信息，有的话就自动登录
    var userInfo = this.getCookie("shujuxiaoyuan_user");
    if (userInfo || userInfo == "") {
      var data = userInfo.split("!");
      console.log(data);
      // 当前已记录有登录信息，则自动执行登录操作 信息格式为 用户名!加密后的密码
      if (data.length == 2) {
        this.Login(data[0], data[1]);
      }
    }
    // 获取本地登录记录
    var loginName = localStorage.getItem("loginName");
    if (loginName) {
      this.dataForm.userName = loginName;
    }
    this.getCaptcha();
  },
  methods: {
    // 远程卡务软件下载
    downloadFile() {
      this.$http({
        url: this.$http.adornUrl("/api/v1/CardService/getOneCardVersion"),
        method: "post",
        data: this.$http.adornData({
          messageContent: "",
          messageType: this.messageType,
        }),
      }).then(({
        data
      }) => {
        if (data.messageCode == 200) {
          let url = data.messageContent.downloadUrl;
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute(
            "download",
            `CardCenter${data.messageContent.versionNo}.exe`
          );
          document.body.appendChild(link);
          link.click();
        } else if (data.messageCode == 500) {
          this.$message.error(data.errorMessage);
        } else {
          this.$message.error("未知错误");
        }
      });
    },
    getCookie(key) {
      var str = document.cookie; // 获取所有cookie
      var arr = str.split("; "); // ["name=pengpeng", "age=18", "desc=shuai"]
      // 遍历数组, 找出 键===key时的 value值
      for (var i = 0; i < arr.length; i++) {
        var data = arr[i].split("="); // ["name", "pengpeng"]
        if (data[0] === key) {
          // 如果相等, 说明找到了
          return data[1];
        }
      }
    },
    // 提交表单
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        let encryptor = new JSEncrypt();
        encryptor.setPublicKey(this.publicKey);
        let loginpassword = encryptor.encrypt(
          this.$md5(this.dataForm.password)
        );
        if (valid) {
          // 判断是否是线上环境（主要是否需要验证码验证）
          if (process.env.NODE_ENV == 'development') {
            this.Login(this.dataForm.userName, loginpassword);
          } else {
            if(localStorage.getItem("user") == 'admin'){
              this.Login(this.dataForm.userName, loginpassword);
            }else{
              this.isCaptcha(this.dataForm.userName, loginpassword);
            }
          }
        }
      });
    },
    // 获取验证码
    getCaptcha() {
      // this.dataForm.uuid = getUUID();
      // this.captchaPath = this.$http.adornUrl(
      //   `/captcha.jpg?uuid=${this.dataForm.uuid}`
      // );
      let timestamp = new Date().valueOf();
      this.$http({
        url: this.$http.adornUrl("/api/v1/PCImageCode"),
        method: "get",
        withCredentials: true,
        responseType: "blob",
      }).then(({
        data
      }) => {
        console.log(data);
        var blob = data;
        var img = document.createElement("img");
        img.onload = function (e) {
          window.URL.revokeObjectURL(img.src);
        };
        this.captchaPath = window.URL.createObjectURL(blob);
      });
    },
    // 验证验证码
    isCaptcha(loginName, loginpassword) {
      this.$http({
        url: this.$http.adornUrl("/api/v1/imageVerifiedCode"),
        method: "post",
        withCredentials: true,
        data: this.$http.adornData({
          messageContent: this.dataForm.captcha,
          messageType: this.messageType,
        }),
      }).then(({
        data
      }) => {
        if (data.messageContent == true && data.messageCode == 200) {
          this.Login(loginName, loginpassword);
        } else {
          this.$message.error("验证码错误");
          this.getCaptcha();
        }
      });
    },
    Login(loginName, loginpassword) {
      // 根据用户guid获取用户的信息
      this.$http({
        url: this.$http.adornUrl("/api/v1/pc-login"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            loginName: loginName,
            loginPassword: loginpassword,
          },
          messageType: this.messageType,
        }),
      }).then(({
        data
      }) => {
        //console.log(data)
        if (data.messageCode == 200) {
          this.userType = data.messageContent.userType;
          if (!data.messageContent.unitGuid) {
            // 没有单位
            if (this.isSysAdmin(this.userType)) {
              this.$message.error("当前系统管理员账户没有所属系统单位");
            } else if (this.isAgent(this.userType)) {
              this.$message.error("当前代理商账户没有所属代理商");
            } else {
              this.$message.error("当前账户管理的学校列表为空");
            }
            this.dataForm.captcha = "";
            this.getCaptcha();
            return;
          }
          // 保存到cookie中
          document.cookie =
            "shujuxiaoyuan_user=" + loginName + "!" + loginpassword;
          // 保存登录名到本地
          localStorage.setItem("loginName", loginName);
          sessionStorage.setItem("administrator", data.messageContent.userGuid);
          sessionStorage.setItem("identity", data.messageContent.identity);
          sessionStorage.setItem("username", data.messageContent.userName);
          sessionStorage.setItem("userType", data.messageContent.userType);
          sessionStorage.setItem("unitName", data.messageContent.unitName);
          sessionStorage.setItem("unitGuid", data.messageContent.unitGuid);
          sessionStorage.setItem("unitType", data.messageContent.unitType);

          this.$store.commit("user/updateSelectedUnigInfo", {
            unitType: data.messageContent.unitType,
            unitGuid: data.messageContent.unitGuid,
            unitName: data.messageContent.unitName,
          });
          if (localStorage.getItem('sidebarLayoutSkin')) {
            this.sidebarLayoutSkin = localStorage.getItem('sidebarLayoutSkin');
          }
          this.$router.push({
            path: "/"
          });
          return;
        }
        if (data.messageCode == 500) {
          this.$message.error(data.errorMessage);
          this.dataForm.captcha = "";
          this.getCaptcha();
          return;
        } else {
          this.$message.error("登录遇到未知错误");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
$bgcolor: #45c2b5;

.bg-bubbles {
  background: linear-gradient(to bottom right, #50a3a2 0, #53e3a6);
  position: absolute;
  // 使气泡背景充满整个屏幕；
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  // 如果元素内容超出给定的宽度和高度，overflow 属性可以确定是否显示滚动条等行为；
  overflow: hidden;
  margin: 0;

  li {
    position: absolute;
    // bottom 的设置是为了营造出气泡从页面底部冒出的效果；
    bottom: -160px;
    // 默认的气泡大小；
    width: 40px;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.15);
    list-style: none;
    // 使用自定义动画使气泡渐现、上升和翻滚；
    animation: square 12s infinite;

    transition-timing-function: linear;

    // 分别设置每个气泡不同的位置、大小、透明度和速度，以显得有层次感；
    &:nth-child(1) {
      left: 5%;
    }

    &:nth-child(2) {
      left: 15%;
      width: 90px;
      height: 90px;
      animation-delay: 2s;
      animation-duration: 7s;
    }

    &:nth-child(3) {
      left: 25%;
      animation-delay: 3s;
    }

    &:nth-child(4) {
      left: 40%;
      width: 60px;
      height: 60px;
      animation-duration: 8s;
      background-color: rgba(255, 255, 255, 0.3);
    }

    &:nth-child(5) {
      left: 70%;
    }

    &:nth-child(6) {
      left: 80%;
      width: 120px;
      height: 120px;
      animation-delay: 3s;
      background-color: rgba(255, 255, 255, 0.2);
    }

    &:nth-child(7) {
      left: 32%;
      width: 160px;
      height: 160px;
      animation-delay: 2s;
    }

    &:nth-child(8) {
      left: 55%;
      width: 20px;
      height: 20px;
      animation-delay: 2s;
      animation-duration: 15s;
    }

    &:nth-child(9) {
      left: 25%;
      width: 10px;
      height: 10px;
      animation-delay: 2s;
      animation-duration: 12s;
      background-color: rgba(255, 255, 255, 0.3);
    }

    &:nth-child(10) {
      left: 85%;
      width: 160px;
      height: 160px;
      animation-delay: 5s;
    }

    &:nth-child(11) {
      animation: squareup 12s infinite;
      left: 35%;
      width: 160px;
      height: 160px;
      animation-delay: 2s;
    }

    &:nth-child(13) {
      animation: squareup 12s infinite;
      left: 45%;
      animation-delay: 3s;
    }

    &:nth-child(14) {
      animation: squareup 12s infinite;
      left: 60%;
      width: 60px;
      height: 60px;
      animation-delay: 5s;
    }
  }

  // 自定义 square 动画；
  @keyframes square {
    0% {
      opacity: 0.5;
      transform: translateY(0px) rotate(45deg);
    }

    25% {
      opacity: 0.75;
      transform: translateY(-400px) rotate(90deg);
    }

    50% {
      opacity: 1;
      transform: translateY(-600px) rotate(135deg);
    }

    100% {
      opacity: 0;
      transform: translateY(-1000px) rotate(180deg);
    }
  }

  // 自定义 square 动画；
  @keyframes squareup {
    100% {
      opacity: 0.5;
      transform: translateY(0px) rotate(45deg);
    }

    50% {
      opacity: 0.75;
      transform: translateY(-400px) rotate(90deg);
    }

    25% {
      opacity: 1;
      transform: translateY(-600px) rotate(135deg);
    }

    0% {
      opacity: 0;
      transform: translateY(-1000px) rotate(180deg);
    }
  }
}

.site-content_down {
  position: absolute;
  top: 0;
  right: 0;
  text-align: center;
  line-height: 50px;
  width: 120px;
  height: 50px;
  background-color: $bgcolor;
  color: #fff;
  cursor: pointer;

  .site-content_meng {
    background-color: rgba(255, 255, 255, 0.1);
  }
}

.site-wrapper.site-page--login {
  min-width: 800px;
  min-height: 600px;
  width: 60vw;
  height: 60vh;
  position: absolute;
  top: 50%;
  // right: 0;
  // bottom: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  // background-color: rgba(38, 50, 56, 0.6);
  overflow: hidden;
  border-radius: 1%;
  // box-shadow: 0px 0px 6px 6px #aaa;
  text-align: center;

  .site-content__wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 0;
    margin: 0;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: transparent;
  }

  .site-content {
    // min-height: 100%;
    height: 100%;
    padding: 0;
    // padding: 30px 500px 30px 30px;
  }

  .brand-info {
    // border-left: 15px solid #fff;
    // margin: 220px 100px 0 90px;
    width: 64%;
    height: 100%;
    // background-image: url(~@/assets/img/index.jpg);
    // background: #eee;
    color: #fff;
  }

  .brand-info__text {
    letter-spacing: 18px;
    margin: 0 0 10px 20px;
    font-size: 50px;
    font-weight: 400;
    text-transform: uppercase;
    user-select: none;
  }

  .brand-info__intro {
    margin: 10px 0 10px 20px;
    font-size: 18px;
    line-height: 1.58;
    // opacity: 0.6;
    color: #fff;
  }

  .login-main {
    position: absolute;
    top: 0;
    right: 0;
    width: 36%;
    height: 100%;
    padding: 10% 3%;
    background-color: #fff;
    border-left: 1px solid #eee;

    /deep/.el-input__inner {
      border: 0;
      border-radius: 0;
      border-bottom: 1px solid #ccc;
    }

    // icon样式
    /deep/.el-input__prefix,
    .el-input__suffix {
      top: 2.8px;
    }

    .site-sidebar__menu-icon {
      font-size: 18px;
    }

    // opacity: 0;
  }

  .login-title {
    // color: #fff;
    font-weight: 600;
    letter-spacing: 0.5vw;
    font-size: 16px;
    padding-bottom: 10%;
  }

  .login-captcha {
    overflow: hidden;

    >img {
      width: 100%;
      cursor: pointer;
    }
  }

  .login-btn-submit {
    width: 80%;
    margin-top: 5%;
    border: 2px solid #fff;
    border-radius: 30px;
    background-color: $bgcolor;
  }

  .login-info {
    width: 100%;
    position: absolute;
    bottom: 10%;
    text-align: center;
    color: #aaa;
    font-size: 13px;
  }
}
</style>
